/*
 * @Author: ji_jy ji_jy@neusoft.com
 * @Date: 2022-05-06 09:20:06
 * @LastEditors: jia.yu jia.yu
 * @LastEditTime: 2022-08-06 18:35:29
 * @FilePath: \framework-plus\src\common\app-control\xhr-interceptor.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import NProgress from 'nprogress'
import { Md5 } from "ts-md5";
import {useUserStore} from "../store/index";

// 添加全局 response 拦截器
axios.interceptors.response.use(
  // 成功回掉
  (res: AxiosResponse) => {
    // 关闭进度条
    NProgress.done()
    // 获取返回数据
    return res.data

  },
  // 失败回掉
  (err) => {
    NProgress.done()
    // 如果是开发模式则在控制台输出完整的错误信息
    console.error('请求错误：' + err)

    return Promise.reject(new Error(err.response.data.msg))

  },
)

// 添加全局 request 拦截器
axios.interceptors.request.use(
  // 发送成功前
  (config: AxiosRequestConfig) => {
    config.baseURL = 'https://intl-api.sydon.cn'
    // config.baseURL = 'https://api.sydon.cn'
    const dict = getSign()
    config.headers.common = {...config.headers.common,...dict}
    console.log(config.headers.common,"common");
    
    NProgress.start()
    return config
  },
  // 发送失败
  (error) => {
    console.log(error)
    return Promise.reject(error)
  },
)
const getSign = () => { 
  const userStore = useUserStore()
  // const appid = 'piirpcbnfetuteqm'
  // const secretKey = 'xsjgyvsepwhrodibsfychvvaeutomilk'
  // const appid = 'thixtwmwygkcdnhd'
  // const secretKey = 'camstbmlzqjsqtteeoeclafjipsqowrh'
  // 沙特
  // const appid = 'tvlpvlyuqgmrscan'
  // const secretKey = 'ukhpbfyggrcdodonkzcvkkeucbjwavyl'

  // 印尼
  const appid = 'grofhxapfdefausc'
  const secretKey = 'dfbdkrnlsjsguqitakopdtcthjdgbrof'
  const source = 'intl'
  const language = userStore.lang
  const random = Math.round(Math.random()*1000800);
  const times =  Date.now().toString().substring(0, 10);
  const sign = Md5.hashStr(secretKey + Md5.hashStr(appid + random + times + source + language))
  return {
    appid:appid,
    source: source,
    language: language,
    random: random,
    times:times,
    sign:sign,
  }
  
}